package com.shyt.security;

import com.alibaba.fastjson.JSON;
import com.shyt.exception.CustomerAuthenticationException;
import com.shyt.util.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;


/***
 * 登录失败处理返回，失败信息进行提示
 */
@Component
@Slf4j
public class LoginFailUtil implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        AuthenticationException e)
            throws IOException, ServletException {
        log.info("进入登陆失败处理,登陆失败处理开始__________________________________");
        String msg = "账号或者密码不正确，请联系管理员";
        if (e instanceof CustomerAuthenticationException) {//新增的异常
            msg = "token信息有误";
        }


        httpServletResponse.setContentType("application/json;charset=utf-8");


        String result = JSON.toJSONString(
                ApiResponse.erro("407", "登录失败", msg));

        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        outputStream.write(result.getBytes(StandardCharsets.UTF_8));


        //outputStream.write(result.getBytes(StandardCharsets.UTF_8));

        outputStream.flush();
        outputStream.close();
        log.info("进入登陆失败处理,登陆失败处理结束__________________________________");

    }
}
